package org.qiaice.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.qiaice.context.BaseContext;
import org.qiaice.entity.Category;
import org.qiaice.mapper.CategoryMapper;
import org.qiaice.result.PageResult;
import org.qiaice.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public PageResult<Category> pageQuery(Integer page, Integer pageSize, String name, Integer type) {
        Page<Category> paged = lambdaQuery()
                .like(StringUtils.hasText(name), Category::getName, name)
                .eq(Objects.nonNull(type), Category::getType, type)
                .orderByDesc(Category::getSort)
                .page(Page.of(page, pageSize));
        return new PageResult<>(paged.getTotal(), paged.getRecords());
    }

    @Override
    public void changeStatus(Integer status, Long id) {
        updateById(Category.builder().id(id).status(status).build());
    }

    @Override
    public List<Category> listByType(Integer type) {
        return lambdaQuery()
                .eq(Objects.nonNull(type), Category::getType, type)
                .orderByDesc(Category::getSort)
                .list();
    }

    @Override
    public void saveCategory(Long id, Integer type, String name, Integer sort) {
        save(Category.builder().id(id).type(type).name(name).sort(sort).build());
    }

    @Override
    public void change(Long id, String name, Integer sort) {
        updateById(Category.builder().id(id).name(name).sort(sort).build());
    }
}
